#include<iostream>
#include<stdio.h>
#include<unistd.h>
#include<string>
#include<string.h>
#include <sys/wait.h>
using namespace std;
#define SIZE 1024
#define SEP " "

char cwd[1024];
char enval[1024];
void getUsercommand(string &command){
	printf("%s@%s:~%s$",getenv("USER"),"VM-20-16-ubuntu",+getenv("PWD"));
	getline(cin,command);
	//cout<<command;
}

void strSplite(string& in,char* out[]){
	int argc=0;
	out[argc++]=strtok(&in[0],SEP);
	while(out[argc++]=strtok(NULL,SEP));

}	

void execute(char* argv[]){
	pid_t id=fork();
	if(id<0){
		cout<<"创建子进程失败!";
		exit(-1);
	}
	if(id==0){
		//子进程的任务
		execvp(argv[0],argv);
		exit(0);
	}
	
	//父进程
	pid_t rid=waitpid(-1,NULL,0);
	if(rid>0){
	}
}

void cd(char * path){
	chdir(path);
	//添加环境变量
	char tmp[1024];
	getcwd(tmp,sizeof(tmp));
	sprintf(cwd,"PWD=%s",tmp);
	putenv(cwd);
}

bool checkBulidin(char * argv[])
{
	if(strcmp(argv[0],"cd")==0){
		char * path=NULL;
		if(argv[1]==NULL) path=".";
		else 
			path=argv[1];
		cd(path);
		return true;
	}
	if(!strcmp(argv[0],"export"))
	{
		if(argv[1]==NULL)return true;
		strcpy(enval,argv[1]);
		putenv(enval);
		return true;
	}
	return false;
}
int main(){
	while(1){
 
      //1.获取命令行提示	
	 string command;
	 char* argv[SIZE];
	 getUsercommand(command);
	 if(!command.size())continue;
	 //2.分割字符
	 strSplite(command,argv);
	 //先判断是否为内建命令
	 bool ret=checkBulidin(argv);
	 //3.创建子进程，进程程序替换
	 if(!ret)
		 execute(argv);
	}
	return 0;
}
